package com.jl15988.chainlog.service;

import com.jl15988.chainlog.config.ChainLogProperties;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

/**
 * 数据清理服务
 * 定时清理过期的监控数据
 */
@Service
@EnableScheduling
@ConditionalOnProperty(prefix = "chain-log.visualization", name = "enabled", havingValue = "true", matchIfMissing = true)
@Slf4j
public class DataCleanupService {

    @Autowired
    private ChainTraceService chainTraceService;

    @Autowired
    private ChainLogProperties chainLogProperties;

    /**
     * 每小时执行一次数据清理
     */
    @Scheduled(fixedRate = 60 * 60 * 1000) // 1小时
    public void cleanupExpiredData() {
        try {
            long retentionTime = chainLogProperties.getVisualization().getDataRetentionTime();
            chainTraceService.cleanExpiredData(retentionTime);
            log.debug("Data cleanup completed, retention time: {}ms", retentionTime);
        } catch (Exception e) {
            log.error("Failed to cleanup expired data", e);
        }
    }
}